package com.smart.controller.sys;

import java.util.Map;
import java.util.Objects;
import com.smart.entity.SysUser;
import javax.annotation.Resource;
import com.smart.util.CommonPage;
import com.smart.util.CommonResult;
import com.smart.util.SysUserUtils;

import cn.hutool.core.util.StrUtil;

import com.smart.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.smart.common.annotation.SysLog;
import com.smart.common.enums.BusinessType;
import com.smart.controller.BaseController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.ibatis.annotations.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author lgb
 * @date 2020年6月11日 下午8:38:22
 * Copyright (C) 深圳工勘科技
 * @说明: 用户管理
 **/
@Api(tags="用户管理")
@RestController("sysUserController")
@RequestMapping("sys/user")
public class UserController extends BaseController{

	@Resource
	private UserService userService;
	@Autowired
    private PasswordEncoder passwordEncoder;
	@ApiOperation("获取个人信息")
    @GetMapping("/profile")
    public CommonResult<SysUser> getPersonalInfo() {
        // 1. 获取用户基本信息
        SysUser user = SysUserUtils.getSysUser();
        return CommonResult.success(user);
    }
	
	@ApiOperation("info/{id} => 用户信息")
    @GetMapping("/info/{id}")
	public CommonResult<SysUser> profile(@PathVariable("id")Long id){
		SysUser sysUser = userService.findById(id);
		return CommonResult.success(sysUser);
	}
	
	@ApiOperation(value="updatePassword => 修改密码",notes="修改当前登陆用户的密码")
    @PutMapping(value="/updatePassword")
    public CommonResult<Integer> updatePassword(
    		@RequestParam(name="password",required=true)String password,
    		@RequestParam(name="newPassword",required=true)String newPassword) {
        Long userId = SysUserUtils.getSysUser().getId();
        SysUser dbUser = userService.findById(userId);
        if (!password.equals(dbUser.getPassword())) {
            return CommonResult.failed("原密码不正确");
        }
        int result = userService.updatePasswordByUserId(userId,newPassword);
        if (result > 0) {
            return CommonResult.success(result);
        }
        return CommonResult.failed();
    }
	/**
     * @param params 参数内容
     *               pageNum
     *               pageSize
     *               username 用户名称
     *               phone 手机号
     *               deptId 部门ID
     * @return 
     **/
    @ApiOperation("list => 根据用户名或姓名分页获取用户列表")
    @GetMapping(value="/list")
    public CommonResult<CommonPage<SysUser>> list(@RequestParam Map<String,Object> params) {
        IPage<SysUser> page = userService.getPage(params);
        return CommonResult.success(CommonPage.restPage(page));
    }
    
    
    @ApiOperation("create => 创建用户信息")
    @SysLog(title="用户管理",businessType=BusinessType.INSERT)
    @PostMapping(value="/create")
    public CommonResult<Integer> create(String carNo,
    		@RequestBody SysUser user){
        String password = user.getPassword();
        SysUser dbUserNameInfo = userService.getByUserName(user.getUsername());
        if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getId(),user.getId())) {
            return CommonResult.failed("该用户已存在");
        }
        if (StrUtil.isBlank(password)) {
            user.setPassword(null);
        } else {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        int count = userService.insertUserAndRole(user,carNo);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }

    @ApiOperation("修改用户信息")
    @SysLog(title="用户管理",businessType=BusinessType.UPDATE)
    @PutMapping(value="/update")
    public CommonResult<Integer> update(String carNo,@RequestBody SysUser user){

        int count = userService.updateUser(user,carNo);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
    
    @ApiOperation("deleteByIds/{ids} => 删除指定用户信息")
    @SysLog(title="用户管理",businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/deleteByIds/{ids}")
    public CommonResult<Integer> deleteByIds(@PathVariable Long[] ids) {
        int count = userService.deleteByIds(ids);
        if (count > 0) {
            return CommonResult.success(count);
        }
        return CommonResult.failed();
    }
    @ApiOperation("update/status/{id} => 修改用户状态")
    @SysLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/update/status/{id}")
    public CommonResult<Integer> update(@PathVariable Long id,String status){
    	try {
    		SysUser user=userService.findById(id);
    		user.setStatus(status);
        	userService.saveOrUpdate(user);
    		return CommonResult.success(1);
		} catch (RuntimeException e) {
			return CommonResult.failed(e.getMessage());
		}
    }
    
    
}